package com.ldw.desensitizer.handler;

import com.alibaba.fastjson.JSON;
import com.ldw.desensitizer.common.CommonResult;
import com.ldw.desensitizer.common.ResponseCode;
import com.ldw.desensitizer.model.User;
import com.ldw.desensitizer.service.annotation.Desensitizer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    public static final String RESPONSE_ANNOTATION = "RESPONSE_ANNOTATION";

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        ServletRequestAttributes ra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest sr = (HttpServletRequest) ra.getRequest();
        Desensitizer desensitizer = (Desensitizer) sr.getAttribute(RESPONSE_ANNOTATION);
        return desensitizer == null ? false : true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        log.info("返回响应，包装进行中");
        CommonResult<Object> result;
        if (body instanceof Boolean || null == body) {
            if ((Boolean) body != true) {
                result = new CommonResult<Object>(body, ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getMessage());
            }
        }
        result = new CommonResult<Object>(body, ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage());
        return result;
    }
}
